package scatter.dict.rest.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import scatter.common.rest.controller.BaseAddUpdateQueryFormController;
import scatter.common.rest.exception.BusinessException;
import scatter.common.rest.tools.StringTool;
import scatter.dict.pojo.dto.DictGroupItemDto;
import scatter.dict.pojo.form.*;
import scatter.dict.pojo.vo.AppDictVo;
import scatter.dict.pojo.vo.DictGroupItemVo;
import scatter.dict.rest.DictConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.web.bind.annotation.RestController;
import scatter.common.rest.controller.BaseAddUpdateQueryFormController;
import scatter.dict.pojo.po.Dict;
import scatter.dict.pojo.vo.DictVo;
import scatter.dict.rest.mapstruct.DictMapStruct;
import scatter.dict.rest.service.IDictService;

import javax.validation.Valid;
/**
 * <p>
 * 字典表 前端控制器
 * </p>
 *
 * @author yw
 * @since 2020-11-23
 */
@RestController
@RequestMapping(DictConfiguration.CONTROLLER_BASE_PATH + "/dict")
@Api(tags = "字典")
public class DictController extends BaseAddUpdateQueryFormController<Dict, DictVo, DictAddForm, DictUpdateForm, DictPageQueryForm> {


    @Autowired
    private IDictService iDictService;

     @Override
	 @ApiOperation("添加字典")
     @PreAuthorize("hasAuthority('Dict:add')")
     @PostMapping
     @ResponseStatus(HttpStatus.CREATED)
     public DictVo add(@RequestBody @Valid DictAddForm addForm) {
         return super.add(addForm);
     }

     @Override
	 @ApiOperation("根据ID查询字典")
     @PreAuthorize("hasAuthority('Dict:queryById')")
     @GetMapping("/{id}")
     @ResponseStatus(HttpStatus.OK)
     public DictVo queryById(@PathVariable String id) {
         return super.queryById(id);
     }

     @Override
	 @ApiOperation("根据ID删除字典")
     @PreAuthorize("hasAuthority('Dict:deleteById')")
     @DeleteMapping("/{id}")
     @ResponseStatus(HttpStatus.NO_CONTENT)
     public boolean deleteById(@PathVariable String id) {
         return super.deleteById(id);
     }

     @Override
	 @ApiOperation("根据ID更新字典")
     @PreAuthorize("hasAuthority('Dict:update')")
     @PutMapping
     @ResponseStatus(HttpStatus.CREATED)
     public DictVo update(@RequestBody @Valid DictUpdateForm updateForm) {
         return super.update(updateForm);
     }

    @Override
	@ApiOperation("不分页查询字典")
    @PreAuthorize("hasAuthority('Dict:getList')")
    @GetMapping("/getList")
    @ResponseStatus(HttpStatus.OK)
    public List<DictVo> getList(DictPageQueryForm listPageForm) {
         return super.getList(listPageForm);
    }

    @Override
	@ApiOperation("分页查询字典")
    @PreAuthorize("hasAuthority('Dict:getPage')")
    @GetMapping("/getPage")
    @ResponseStatus(HttpStatus.OK)
    public IPage<DictVo> getPage(DictPageQueryForm listPageForm) {
         return super.getPage(listPageForm);
    }

    @ApiOperation("根据字典组编码查询字典项")
    @GetMapping("/getItems")
    @ResponseStatus(HttpStatus.OK)
    public List<DictVo> getItems(@Valid DictItemsQueryForm queryForm) {
        return posToVos(iDictService.getItemsByGroupCode(queryForm));
    }
    
    @ApiOperation("根据字典组编码查询分组字典项")
    @GetMapping("/getGroupItems")
    @ResponseStatus(HttpStatus.OK)
    public List<DictGroupItemVo> getGroupItems(@Valid DictItemsQueryForm queryForm) {

        List<DictGroupItemDto> groupItemsByGroupCode = iDictService.getGroupItemsByGroupCode(queryForm);
        return DictMapStruct.INSTANCE.dictGroupItemDtosToDictGroupItemVos(groupItemsByGroupCode);
    }
    
    @ApiOperation("根据字典组编码查询字典项")
    @GetMapping("/app/getItems")
    @ResponseStatus(HttpStatus.OK)
    public List<AppDictVo> getAppItems(@Valid DictItemsQueryForm queryForm) {
        List<Dict> dicts = iDictService.getItemsByGroupCode(queryForm);

        return DictMapStruct.INSTANCE.posToAppVos(dicts);
    }

    @ApiOperation("根据字典组编码查询字典组")
    @GetMapping("/getGroups")
    @ResponseStatus(HttpStatus.OK)
    public List<DictVo> getGroups(@Valid DictGroupsQueryForm queryForm) {
        return posToVos(iDictService.getGroupsByGroupCodes(queryForm));
    }

    @ApiOperation("生成java字典枚举")
    @PreAuthorize("hasAuthority('Dict:generate:java:enum')")
    @PostMapping("/generateJavaEnum/{dictId}")
    @ResponseStatus(HttpStatus.CREATED)
    public String generateJavaEnum(@PathVariable String dictId) {
        Dict dictGroup = iDictService.getById(dictId);
        if (!dictGroup.getIsGroup()) {
            throw new BusinessException("传入的字典id不是字典组");
        }
        List<Dict> children = iDictService.getChildren(dictId);
        List<Dict> dictItems = children.stream().filter(d -> !d.getIsGroup()).collect(Collectors.toList());

        String template = "\n" +
                "    /**\n" +
                "     * #{groupMemo}\n" +
                "     */\n" +
                "    public enum #{groupClassPrefix}GroupCode implements IDictGroup {\n" +
                "        #{groupCode};\n" +
                "\n" +
                "        @Override\n" +
                "        public String groupCode() {\n" +
                "            return this.name();\n" +
                "        }\n" +
                "    }\n" +
                "\n" +
                "    /**\n" +
                "     * #{itemMemo}\n" +
                "     */\n" +
                "    public enum #{itemClassPrefix}DictItem implements IDictItem {\n" +
                "        #{items}\n" +
                "        ;\n" +
                "\n" +
                "        @Override\n" +
                "        public String itemValue() {\n" +
                "            return this.name();\n" +
                "        }\n" +
                "\n" +
                "        @Override\n" +
                "        public String groupCode() {\n" +
                "            return #{groupClassPrefix}GroupCode.#{groupCode}.groupCode();\n" +
                "        }\n" +
                "    }";


        Map<String,String> params = new HashMap<>();
        params.put("#{groupMemo}",dictGroup.getName());
        params.put("#{groupClassPrefix}", StrUtil.upperFirst(StringTool.lineToHump(dictGroup.getCode())));
        params.put("#{groupCode}",dictGroup.getCode());

        params.put("#{itemMemo}",dictGroup.getName() + "字典项");
        params.put("#{itemClassPrefix}",params.get("#{groupClassPrefix}"));

        List<String> items = new ArrayList<>();
        for (Dict dictItem : dictItems) {
            items.add("        " + dictItem.getValue() + ",     // " + dictItem.getName() + FileUtil.getLineSeparator());
        }

        params.put("#{items}",items.stream().collect(Collectors.joining(" ")));


        for (String tempKey : params.keySet()) {
            template = template.replace(tempKey,params.get(tempKey));
        }


        return template;
    }



}
